package com.yeziji.devops.sql.constructor;

import cn.hutool.core.util.StrUtil;
import com.yeziji.devops.common.expcetion.SqlBuilderException;
import com.yeziji.devops.common.msg.SqlBuilderErrorMsg;
import com.yeziji.devops.constant.SqlExecuteTypeEnum;
import com.yeziji.devops.sql.SqlBuilderFactory;
import com.yeziji.devops.sql.base.SqlConstructorBase;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

/**
 * 删除 SQL 构造器
 *
 * @author gzkemays
 * @since 2023/01/08 12:16 PM
 */
@Data
@SuperBuilder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class DeleteSqlConstructor extends SqlConstructorBase {
    /**
     * 根据 id 删除
     * <p>
     * 根据 id 删除，可以直接传入 id 执行 delete by id
     * </p>
     */
    private Object id;

    /**
     * 主键的字段名
     * <p>
     * 主键的字段名，默认为 id
     * </p>
     */
    private String primaryKey = "id";

    @Override
    protected void check() {
        super.setType(SqlExecuteTypeEnum.DELETE.getValue());
        super.check();

        if (this.id == null && StrUtil.isBlank(super.wrapper)) {
            // id == null 且 wrapper 为空时抛出条件为空异常
            throw new SqlBuilderException(SqlBuilderErrorMsg.WRAPPER_IS_EMPTY);
        }
    }

    @Override
    public String buildSql() {
        if (StrUtil.isNotBlank(super.sql)) {
            return super.sql;
        }

        this.check();
        return new SqlBuilderFactory().getSqlBuilder(SqlExecuteTypeEnum.DELETE, this).execute();
    }
}
